package com.nftturboauth.controller;

import com.nftturboapi.user.request.UserRegisterRequest;
import com.nftturboapi.user.response.UserOperatorResponse;
import com.nftturboapi.user.service.UserFacadeService;
import com.nftturboauth.exception.AuthException;
import com.nftturboauth.param.RegisterParam;
import com.nftturboweb.vo.Result;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.nftturboapi.notice.constant.NoticeConstant.CAPTCHA_KEY_PREFIX;
import static com.nftturboauth.exception.AuthErrorCode.VERIFICATION_CODE_WRONG;

/**
 * 认证相关接口
 *
 * @author Hollis
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference(version = "1.0.0", retries = 0)
    private UserFacadeService userFacadeService;

    @PostMapping("/register")
    public Result<Boolean> register(@Valid @RequestBody RegisterParam registerParam) {
        //验证码校验
        String cachedCode = redisTemplate.opsForValue().get(CAPTCHA_KEY_PREFIX + registerParam.getTelephone());
//        if (!StringUtils.equalsIgnoreCase(cachedCode, registerParam.getCaptcha())) {
//            throw new AuthException(VERIFICATION_CODE_WRONG);
//        }

        //注册
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setTelephone(registerParam.getTelephone());
        userRegisterRequest.setInviteCode(registerParam.getInviteCode());

        UserOperatorResponse registerResult = userFacadeService.register(userRegisterRequest);

        if(registerResult.getSuccess()){
            return Result.success(true);
        }
        return Result.error(registerResult.getResponseCode(), registerResult.getResponseMessage());
    }
}
